package com.sunseen.capacitormachine;

import android.app.AlarmManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseIntArray;

import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;

import com.sunseen.capacitormachine.common.MethodUtil;
import com.sunseen.capacitormachine.common.SharePreferenceUtil;
import com.sunseen.capacitormachine.common.customview.AlarmView;
import com.sunseen.capacitormachine.common.event.ConnectStateChangeEvent;
import com.sunseen.capacitormachine.commumication.mqtt.HiveMqttService;
import com.sunseen.capacitormachine.commumication.mqtt.bean.AlarmJsonObj;
import com.sunseen.capacitormachine.commumication.mqtt.event.SendJsonObjEvent;
import com.sunseen.capacitormachine.commumication.serialport.PlcService;
import com.sunseen.capacitormachine.commumication.serialport.SurgeService;
import com.sunseen.capacitormachine.commumication.serialport.bean.ChangeBatchBean;
import com.sunseen.capacitormachine.commumication.serialport.event.AlarmEvent;
import com.sunseen.capacitormachine.commumication.serialport.event.ChainMoveOneStepEvent;
import com.sunseen.capacitormachine.commumication.serialport.event.CmdEvent;
import com.sunseen.capacitormachine.commumication.serialport.event.CmdSendFailedEvent;
import com.sunseen.capacitormachine.commumication.serialport.event.HideAlarmViewEvent;
import com.sunseen.capacitormachine.commumication.tcp.TcpService;
import com.sunseen.capacitormachine.modules.login.LoginFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import me.yokeyword.fragmentation.SupportActivity;

/**
 * @author zest
 */
public class MainActivity extends SupportActivity {

    private String[] alarmString;
    private String[] offLineAlarmString;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //隐藏系统状态栏和导航按键栏
        hideSystemUI();
        //设置透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //设置透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        //去除标题栏
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        setContentView(R.layout.activity_main);
        //设置时区为中国大陆时区
        final AlarmManager mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        if (mAlarmManager != null) {
            mAlarmManager.setTimeZone("GMT+8");
        }
        Resources resources = getResources();
        alarmString = resources.getStringArray(R.array.machine_abnormal);
        offLineAlarmString = resources.getStringArray(R.array.disconnect_info);
        startService(new Intent(MainActivity.this, HiveMqttService.class));
        startService(new Intent(MainActivity.this, TcpService.class));
        startService(new Intent(MainActivity.this, SurgeService.class));
        startService(new Intent(MainActivity.this, PlcService.class));

        boolean loginState = SharePreferenceUtil.getInstance(getApplicationContext()).getBoolean(SharePreferenceUtil.LOGIN_STATE, false);
        if (loginState) {
            loadRootFragment(R.id.fl_container, new MainFragment());
        } else {
            loadRootFragment(R.id.fl_container, new LoginFragment());
        }
//        if(CapacitorApp.getList() != null) {
//            String batchStatus = SharePreferenceUtil.getInstance(getApplicationContext()).getString(SharePreferenceUtil.CHANGE_BATCH,"");
//            Log.e("xiaochunhui--", "batchStatus = " + batchStatus);
//            if(!TextUtils.isEmpty(batchStatus)){
//                String[] strings = batchStatus.split(",");
//                for (int i = 0; i < strings.length; i ++) {
//                    String[] strs = strings[i].split("-");
//                    if(strs.length == 2){
//                        ChangeBatchBean changeBatchBean = new ChangeBatchBean();
//                        changeBatchBean.setBatchid(strs[0]);
//                        changeBatchBean.setStatus(Integer.valueOf(strs[1]));
//                        CapacitorApp.getList().add(changeBatchBean);
//                    }
//                }
//            }
//        }
        alarmView = new AlarmView(this);
        EventBus.getDefault().register(this);
    }

    private AlarmView alarmView;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAlarmEvent(AlarmEvent event) {
        final List<String> stringList = new ArrayList<>();
        final SparseIntArray intArray = event.getIntArray();
        for (int i = 0, size = intArray.size(); i < size; i++) {
            stringList.add(alarmString[intArray.get(i)]);
        }
        EventBus.getDefault().post(new SendJsonObjEvent(new AlarmJsonObj("",
                System.currentTimeMillis() / 1000, stringList)));
        alarmView.setAlarmInfo(stringList);
        alarmView.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChainMoveOneStep(ChainMoveOneStepEvent event) {
        if (alarmView != null && alarmView.isShowing()) {
            alarmView.hide();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHideAlarmView(HideAlarmViewEvent event) {
        if (alarmView != null && alarmView.isShowing()) {
            alarmView.hide();
        }
    }

    private void hideSystemUI() {
        // Enables regular immersive mode.
        // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
        // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        // Set the content to appear under the system bars so that the
                        // content doesn't resize when the system bars hide and show.
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        // Hide the nav bar and status bar
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }

    private boolean[] offLineFlags = new boolean[]{false, false, false, false, false};

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onConnectStateChange(ConnectStateChangeEvent event) {
        final List<String> stringList = new ArrayList<>();
        offLineFlags[event.getType()] = event.isDisconnect();
        for (int i = 0, length = offLineFlags.length; i < length; i++) {
            if (offLineFlags[i]) {
                stringList.add(offLineAlarmString[i]);
            }
        }
        if (!stringList.isEmpty()) {
            if (alarmView.offLineFlagDifferent(offLineFlags)) {
                //暂停机器运行
                EventBus.getDefault().post(new CmdEvent(PlcService.PAUSE));
                alarmView.setOffLineInfo(stringList);
                EventBus.getDefault().post(new SendJsonObjEvent(new AlarmJsonObj("", System.currentTimeMillis(), stringList)));
                if (!alarmView.isShowing()) {
                    alarmView.show();
                }
            }
        } else {
            alarmView.tryHide();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCmdSendFailed(CmdSendFailedEvent event) {
        if (event.getFailedType() == 1) {
            Toast.makeText(MainActivity.this, getString(R.string.plc_no_reply), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, getString(R.string.plc_reply_oxBB), Toast.LENGTH_SHORT).show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onChangeBatchEvent(ChangeBatchBean changeBatchBean){//检测到生产列表中最前面的生产批次完成
//        if(changeBatchBean.getStatus() != -1){
//            //changeBatchBean 2 启动生产 1 生产中    3 已生产
//            // http:生产状态 0 待生产  1 生产中  2 已生产
//            if(changeBatchBean.getStatus() == 1) {//上报信息
//                MethodUtil.updateBatchProduceStatus(changeBatchBean.getBatchid(), 1);
//                if (alarmView.isShowing()) {
//                    alarmView.hide();
//                }
//            } else if(changeBatchBean.getStatus() == 3) {
//                MethodUtil.updateBatchProduceStatus(changeBatchBean.getBatchid(), 2);
//                if(CapacitorApp.getList().size() > 0){
//                    CapacitorApp.getList().remove(0);
//                }
//                final List<String> stringList = new ArrayList<>();
//                stringList.add("批次：" + changeBatchBean.getBatchid() + " 换批完成");
//                alarmView.setAlarmInfo(stringList);
//                if (!alarmView.isShowing()) {
//                    alarmView.show();
//                }
//            } else if(changeBatchBean.getStatus() == 2){
//                MethodUtil.updateBatchProduceStatus(changeBatchBean.getBatchid(), 0);
//                if (alarmView.isShowing()) {
//                    alarmView.hide();
//                }
//            }
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
